package com.example.mq.server.core;

import com.example.mq.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MSGQueue {
    // 队列唯一名字
    private String name;
    // 队列是否持久化，默认是不持久化的
    private boolean durable = false;
    // 队列是否是被独占的，待实现
    private boolean exclusive = false;
    // 队列是否自动删除，待实现
    private boolean autoDelete = false;
    // 队列的额外功能，待实现
    private Map<String,Object> arguments = new HashMap<>();
    // 订阅者
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    // 记录轮询到哪个消费者了
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String,Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    // 增加消费者
    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }
    // 挑选消费者消费消息，这里采取轮询的方式
    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            // 说明当前并没有消费者，直接返回空
            return null;
        }
        // 查看轮询到哪个消费者了
        int index = consumerSeq.get() % consumerEnvList.size();
        // 向后推移一个消费者
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }


    // 添加测试方法
    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }
    public Object getArguments(String key) {
        return arguments.get(key);
    }
}
